package test;

import javax.microedition.media.control.MIDIControl;

public class NotesOffThread extends Thread {

	private static final int NOTE_OFF = 0x80;

	private Note[] notes;

	private MIDIControl midiControl;

	private int channel;

	public NotesOffThread(MIDIControl midiControl, Note[] notes, int channel) {
		// copia os valores aqui
		this.midiControl = midiControl;
		this.channel = channel;

		this.notes = new Note[notes.length];
		for (int i = 0; i < notes.length; i++) {
			this.notes[i] = notes[i];
		}

		// bubblesort nojentão
		for (int i = 0; i < this.notes.length; i++) {
			for (int j = i + 1; j < this.notes.length; j++) {
				if (this.notes[j].getEndTime() < this.notes[i].getEndTime()) {
					// swap
					Note tmp = this.notes[i];
					this.notes[i] = this.notes[j];
					this.notes[j] = tmp;
				}
			}
		}
	}

	public void run() {
		long startTime = System.currentTimeMillis();
		int counter = 0;
		while (counter < this.notes.length) {
			while (System.currentTimeMillis() - startTime < this.notes[counter]
					.getEndTime()) {
				// wait, doing nothing...
			}
			midiControl.shortMidiEvent(NOTE_OFF | this.channel,
					this.notes[counter].getTone(), this.notes[counter]
							.getIntensity());
			counter++;
		}
	}

}
